import React, { PureComponent } from 'react'
import Info from './info'
import Pie from '../chart/base-pie'
import '../../../css/device.scss'
// import * as d3 from 'd3'
import * as d3 from 'd3'
// import * as transtion from 'd3-transition'
import { setTitle, scale, tooltip } from '../chart/util/common'
const d3transition = d3.transition
const select = d3.select
function fn () {

}
/*文字偏移计算，用于文字居中*/
function getTextOffset (text = '') {
    const reg = /^[a-zA-Z]+$///a-z A-z判断是否为字母
    let len = 0
    text.split('').forEach(t => {
        if (reg.test(t)) {
            len += 2 * scale
        } else {
            len += 4 * scale
        }
    })

    return len
}

const colors = {
    on: {
        color: '#00B797',
        text: '正常'
    },
    error: {
        color: '#D23F49',
        text: '故障'
    },
    off: {
        color: '#E7DB79',
        text: '关机'
    }
}
class Device extends PureComponent {
    state = {
        x: -1000,
        y: -1000,
        content: []
    }

    componentWillUpdate (nextProps) {
        if (nextProps.types !== this.props.types) {
            this.renderDataToChart(nextProps.types)
        }
    }

    renderDataToChart = (data) => {
        const {openDetail = fn, tooltipPos = 'bottom'} = this.props
        /*计算设备的初始位置start和长度*/
        /*设备所占位置为产线长度的90%*/
        /*除以设备的权值与设备间距之和得到单位长度的大小*/
        const signalLen = this.width * 0.9 / data.reduce(function (a, b) {
                return a + b.len + 0.4
            }, 0).toFixed(1)
        /*设备在产线对应的开始位置*/
        let nowLen = 0.2 * signalLen + this.width * 0.05
        /*计算出设备位置，根据设备长度计算出设备长度*/
        data.forEach((d, i) => {
            d.start = nowLen
            d.width = +d.len * signalLen
            nowLen += d.width + 0.4 * signalLen
        })

        /*根据data数据画设备*/
        this.dataNodes.selectAll('rect').remove()
        const rects = this.dataNodes.selectAll('rect')
            .data(data)
        rects.enter()
            .append('rect')
            .attr('x', (data) => {
                return data.start + this.margin.left
            })
            .attr('y', this.height * 0.4)
            .attr('rx', 2 * scale)
            .attr('ry', 2 * scale)
            .attr('width', function (data) {
                return data.width
            })
            .attr('height', this.height * 0.5)
            .attr('cursor', 'pointer')
            .style('fill', d => colors[d.status] && colors[d.status].color)
            /*tooltip*/
            .on('mouseover', (data, index, dom) => {
                const targetPos = dom[index].getBoundingClientRect()
                let yPos = 'bottom'
                if (tooltipPos.indexOf('top') !== -1) {
                    yPos = 'top'
                }
                if (tooltipPos.indexOf('bottom') !== -1) {
                    yPos = 'bottom'
                }

                this.setState({
                    x: d3.event.pageX,
                    y: targetPos[yPos],
                    content: [
                        {
                            field: '设备名',
                            value: data.deviceName
                        }, {
                            field: '设备品牌',
                            value: data.deviceBand
                        }, {
                            field: '设备编号',
                            value: data.deviceId
                        }, {
                            field: '操作人员',
                            value: data.operator
                        }, {
                            field: '当前状态',
                            value: colors[data.status].text
                        }
                    ]
                })
            })
            .on('mouseout', () => {
                this.setState({
                    x: -1000,
                    y: -1000
                })
            })
            .on('click', (data, index, dom) => {
                openDetail(data)
                this.setState({
                    x: -1000,
                    y: -1000
                })
            })

        /*画设备名称*/
        this.dataNodes.selectAll('text').remove()
        const texts = this.dataNodes.selectAll('text')
            .data(data)

        texts.exit().remove()
        texts.enter()
            .append('text')
            .attr('x', (data) => {
                return data.start + this.margin.left + data.width / 2 - getTextOffset(data.deviceName)
            })
            .attr('y', this.height * 0.25 + this.margin.top)
            .text(d => d.deviceName)
            .style('fill', '#00b797')
            .style('font-size', .75 + 'rem')
    }

    initChart = () => {
        const clientWidth = this.refs.chart.clientWidth
        const clientHeight = this.refs.chart.clientHeight

        this.svg = select(this.refs.chart)
        this.svg.selectAll('g').remove()
        this.margin = {top: 0, right: 20 * scale, bottom: 0, left: 20}
        this.svg.attr('width', clientWidth)
        this.svg.attr('height', clientHeight)
        this.width = clientWidth - this.margin.left - this.margin.right
        this.height = clientHeight - this.margin.top - this.margin.bottom
        /*分割线*/
        this.svg.append('g')
            .append('line')
            .attr('x1', this.margin.left)
            .attr('x2', this.margin.left + this.width)
            .attr('y1', this.height * 0.65 - 1)
            .attr('y2', this.height * 0.65 - 1)
            .attr('width', this.width)
            .attr('height', 1)
            .attr('stroke', '#666')
            .attr('stroke-width', 2 * scale)
            .attr('stroke-dasharray', '5 2')
            .style('fill', 'none')

        // var t = d3transition()
        //     .duration(3000)
        //
        // console.log(d3transition)
        // console.log(select(board))
        // select(board)
        //     .transition(t)
        // select(board).attr('x', this.margin.left + this.width)
        // d3transition
        //     .selection()
        //     .selectAll(board)
        //     .transition(t)
        // select('body')
        //     .transition()
        //     .style('background-color', 'red')

        /*产线*/
        this.svg.append('g')
            .append('rect')
            .attr('x', this.margin.left)
            .attr('y', this.height * 0.5)
            .attr('width', this.width)
            .attr('height', this.height * 0.3)
            .attr('stroke', '#00b797')
            .attr('stroke-width', 2 * scale)
            .style('fill', 'none')
            .attr('ry', 2 * scale)
            .attr('rx', 2 * scale)

        // 加工板
        const total = Math.min(this.props.types.length, 5)
        const width = this.width / this.props.types.reduce((a, b) => a + b.len, 0) / 3
        const board = this.svg.append('g')
            .append('rect')
        board.attr('x', this.margin.left + 10)
            .attr('y', this.height * 0.55)
            .attr('width', width)
            .attr('height', this.height * 0.2)
            .attr('fill', 'rgba(96, 125, 139, .8)')
            .attr('ry', 2 * scale)
            .attr('rx', 2 * scale)
            .attr('class', 'board')

        /*设备*/
        this.dataNodes = this.svg.append('g')
        this.renderDataToChart(this.props.types)
    }

    componentDidMount = () => {
        this.initChart()
        window.addEventListener('resize', this.initChart)
    }

    componentWillUnmount = () => {
        window.removeEventListener('resize', this.initChart)
    }

    /*tooltip 显示位置*/
    getPos = () => {
        const pos = {left: this.state.x + 'px', top: this.state.y + 'px'}
        const {openDetail = fn, tooltipPos = 'bottom'} = this.props
        let xPos = 0
        let yPos = 0
        if (tooltipPos.indexOf('left') !== -1) {
            xPos = 100
        }

        if (tooltipPos.indexOf('top') !== -1) {
            yPos = 100
        }
        pos.transform = `translate(-${xPos}%,-${yPos}%)`
        return pos
    }

    render = () => <div style={{width: '100%', height: '100%'}}>
        <svg style={{width: '100%', height: '100%'}} id="svg" ref="chart"/>
        <div className="device-tooltip" style={this.getPos()}>
            {this.state.content.map(c => {
                return <p key={`device-chart-${c.field}`}>{c.field}: {c.value}</p>
            })}
        </div>
    </div>

}

export default Device